import axios from 'axios'
import store from '@/store'
import jsonBig from 'json-bigint'
import router from '@/router'
import { resetToken } from '@/api/user'
const request = axios.create({
  baseURL: 'http://192.168.2.8:8000' // 基础路径
})

console.log(request.defaults.transformResponse)
request.defaults.transformResponse = [
  function (data) {
    try {
      return jsonBig.parse(data)
    } catch (err) {
      return {}
    }
  }
]

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  // console.log(store.state.tokens)
  console.log(config)
  //  {
  if (store.state.tokens) {
    if (config.url.indexOf('/v1_0/authorizations') === -1) {
      config.headers.Authorization = `Bearer ${store.state.tokens.token}`
    } else {
      config.headers.Authorization = `Bearer ${store.state.tokens.refresh_token}`
    }
  }
  // } else {
  //
  // }
  return config
}, function (error) {
  // 对请求错误做些什么

  console.log(error)
  return Promise.reject(error)
})

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, async function (error) {
  // 对响应错误做点什么
  console.log(error)
  if (error.response && error.response.status === 401) {
    if (!store.state.tokens || !store.state.tokens.refresh_token) {
      router.push('/login')
      return
    } else {
      try {
        // 如果token过期了就用refresh_token重新获取token
        const res = await resetToken()
        console.log(res)
        store.commit('setUserToken', {
          token: res.data.data.token,
          refresh_token: store.state.tokens.refresh_token
        })
        store.dispatch('loadUserInfo')
      } catch (error) {
        console.log(error)
        router.push('/login')
      }
    }
  }
  return Promise.reject(error)
})

export default request
